package com.zsc.wxm.ysh.anjo.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 描述：
 *
 * @author playmaker
 * @since 2021/2/10 0:16
 */
@Slf4j
public class LocationUtil {
    /**
     * 腾讯位置服务
     */
    private static final String ADDRESS_KEY = "SJUBZ-PBHCD-P3O4Q-HOKK4-CPHZ2-TYBFM";

    /**
     * 获取登录城市
     * @param request
     * @return
     */
    public static String getLocationCity(HttpServletRequest request){
        String ip = IpUtil.getIpAddr(request);
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL("https://apis.map.qq.com/ws/location/v1/ip?key=" + ADDRESS_KEY + "&ip=" + ip);
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间，单位毫秒
            connection.setConnectTimeout(3000);

            // 设置读取数据超时时间，单位毫秒
            connection.setReadTimeout(3000);

            // 是否打开输出流 true|false
            connection.setDoOutput(true);

            // 是否打开输入流true|false
            connection.setDoInput(true);

            // 提交方法POST|GET
            connection.setRequestMethod("GET");

            // 是否缓存true|false
            connection.setUseCaches(false);

            // 打开连接端口
            connection.connect();
            // 往对端写完数据对端服务器返回数据,以BufferedReader流来读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));

            StringBuilder buffer = new StringBuilder();

            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            String city = null;
            JSONObject jsonObject = JSON.parseObject(buffer.toString());
            if (jsonObject != null && !jsonObject.isEmpty() && jsonObject.getIntValue("status") == 0) {
                city = jsonObject.getJSONObject("result").getJSONObject("ad_info").getString("city");
            }
            return city;
        } catch (Exception e) {
            log.error(ExceptionUtil.getMessage(e));
            return "";
        }
    }
}
